/**
 * ConceptualBackupDAO.java
 * Created on March 27, 2007, 3:59 PM
 *
 *
 */
 
package edu.byu.isys413.jjenkins.data;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * This class includes all the CRUD methods that interact with the database.
 * @author Jeff Jenkins
 * @version 1.0
 */
public class ConceptualBackupDAO {
    
    /** Creates a new instance of ConceptualBackupDAO */
    public ConceptualBackupDAO() {
    }
    
    
    private static ConceptualBackupDAO instance = null;
    
    
        /* This method implements the singleton pattern. It insures that only
         * on instance of ConceptualBackupDAO exists
         *
         * @return: ConceptualBackupDAO instance */
    
    /**
     * gets the single instance
     * @return 
     */
    public static synchronized ConceptualBackupDAO getInstance() {
        if (instance == null) {
            instance = new ConceptualBackupDAO();
        }
        return instance;
    }
    
         /* This method creates a new ConceptualBackupBO with a unique QUID, puts the interest
          * in cache, and then returns it to the calling method.
          *
          * @return: ConceptualBackupBO
          * @throws: DataException
          */
    
    /**
     * creates
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return 
     */
    public ConceptualBackupBO create() throws DataException {
        try {
            
            String id = GUID.generate();
            ConceptualBackupBO object = new ConceptualBackupBO();
            object.setId(id);
            Cache.getInstance().put(object.getId(), object);
            return object;
        } catch (Exception e) {
            throw new DataException("Could not create GUID", e);
        }
        
    }
    
    
    /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     * 
     * 
     * @return ConceptualBackupBO
     * @param id 
     * @throws DataException 
     */
    public synchronized ConceptualBackupBO read(String id) throws DataException {
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        ConceptualBackupBO object = (ConceptualBackupBO)cache.get(id);
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // If the item is not in cache a connection is checked out and
            // The item is read from the database.
            if(object == null){
                try {
                    //reads in object
                    object = read(id, conn);
                    
                }catch (SQLException e) {
                    conn.rollback();
                    throw new DataException("Could not retrieve record for id=" + id, e);
                }
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve record for id=" + id, e);
        }
        
        // Return object
        return object;
    }
    
    /**
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  @Par: String: id, Connection conn
     *  @Return: ConceptualBackupBO
     *  @throws: DataException, SQLException
     */
    synchronized ConceptualBackupBO read(String id, Connection conn) throws SQLException, DataException {
        
        
        // Checks to see if the item is in cache
        Cache cache = Cache.getInstance();
        ConceptualBackupBO object = (ConceptualBackupBO)cache.get(id);
        
        // Quieries that database
        if(object == null){
            
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM conceptual_backup WHERE conceptual_backup_id = ?");
            pstmt.setString(1, id);
            pstmt.execute();
            ResultSet rs = pstmt.getResultSet();
            
            if (rs.next()) {
                object = new ConceptualBackupBO();
                object.setId(rs.getString("conceptual_backup_id"));
                object.setPrice(rs.getDouble("price"));
                object.setDate(rs.getDate("date_made"));
                
                
                
                // Sets already in database
                object.setObjectAlreadyInDB(true);
                
                // adds to cache
                cache.put(object.getId(), object);
                
            }else{
                throw new DataException("Object was not found in the database.");
            }
        }
        
        
        // returns object
        return object;
    }
    
    /**
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an object
     * into the database.
     * 
     * 
     * @par ConceptualBackupBO object
     * @param object 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    public synchronized void save(ConceptualBackupBO object) throws DataException {
        try {
            
            
            // retrieve a database connection from the pool
            ConnectionPool connPool = ConnectionPool.getInstance();
            
            Connection conn = connPool.get();
            
            
            try {
                
                // Saves Interest
                save(object, conn);
                
            }catch (SQLException e) {
                conn.rollback();
                throw new DataException("Could not save record for" + object.getId(), e);
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            // touch the cache for the object
            Cache.getInstance().touch(object.getId());
            
            
            
        } catch (DataException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        } catch (SQLException e) {
            throw new DataException("Could not save record for" + object.getId(), e);
        }
        
        
    }
    
    /**
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection objects or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the CustomerDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  object needs to be inserted or updated.
     *
     *  @par: ConceptualBackupBO, Connection
     *  @throws: SQLException, DataException
     */
    synchronized void save(ConceptualBackupBO object, Connection conn) throws SQLException, DataException {
        
        // check the dirty flag in the object.  if it is dirty,
        // run update or insert
        if (object.isDirty()) {
            if (object.isObjectAlreadyInDB()) {
                update(object, conn);
            }else{
                insert(object, conn);
            }
            object.setDirty(false);
        }
        
        
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @Par ConceptualBackupBO object
     */
    private synchronized void update(ConceptualBackupBO object, Connection conn) throws SQLException, DataException {
        
        PreparedStatement pstmt = conn.prepareStatement("UPDATE conceptual_backup SET conceptual_backup_id = ?, price = ?, date_made = ? WHERE conceptual_backup_id = ?");
        pstmt.setString(1, object.getId());
        pstmt.setDouble(2, object.getPrice());
        pstmt.setDate(3, object.getDate());
        pstmt.execute();
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     *
     * @Par ConceptualBackupBO object
     */
    private synchronized void insert(ConceptualBackupBO object, Connection conn) throws SQLException, DataException {
        
        // Creates prepared statemetn
        PreparedStatement pstmt = conn.prepareStatement("INSERT INTO conceptual_backup VALUES(?, ?, ?)");
        pstmt.setString(1, object.getId());
        pstmt.setDouble(2, object.getPrice());
        pstmt.setDate(3, object.getDate());
        
        //Executes prepated statement
        pstmt.execute();
        
        //Sets already in database true
        object.setObjectAlreadyInDB(true);
        
    }
    
    
    /* We intentionally do not allow a ConceptualBackupBO object to be deleted because
     * it could mess up relationships in the database. Obmitting the delete
     * also prevents fraud. */
    
    /**
     * delete method deletes the data out from the database
     * @param customer 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     */
    public synchronized void delete(CustomerBO customer)throws DataException{
    /* We intentionally do not allow a ConceptualBackupBO object to be deleted because
     * it could mess up relationships in the database. Obmitting the delete
     * also prevents fraud. */
        throw new DataException("You can not delete a ConceptualBackupBO");
    }
  
    
 /**
     * This is the public read statement.  It loads an existing record
     * from the database.
     *
     * @param String: id
     * @return ConceptualBackupBO
     * @throws DataException
     */
    public synchronized ConceptualBackupBO getLatest() throws DataException {
        

        ConceptualBackupBO object = null;
        try {
            
            // Gets connection
            ConnectionPool connPool = ConnectionPool.getInstance();
            Connection conn = connPool.get();
            
            // If the item is not in cache a connection is checked out and
            // The item is read from the database.
            if(object == null){
                try {
                    //reads in object
                    object = getLatest(conn);
                    
                }catch (SQLException e) {
                    conn.rollback();
                    throw new DataException("Could not retrieve record", e);
                }
            }
            
            // connection committs and is returned.
            conn.commit();
            connPool.release(conn);
            
            
            
        } catch (SQLException e) {
            throw new DataException("Could not retrieve record", e);
        } catch (DataException e) {
            throw new DataException("Could not retrieve record", e);
        } catch (ConnectionPoolException e) {
            throw new DataException("Could not retrieve record", e);
        }
        
        // Return object
        return object;
    }
    
    /**
     * gets the latest information
     * @param conn 
     * @throws java.sql.SQLException 
     * @throws edu.byu.isys413.jjenkins.data.DataException 
     * @return latest
     */
    public ConceptualBackupBO getLatest(Connection conn) throws SQLException, DataException{
        
        PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM conceptual_backup WHERE date_made = (Select max(date_made) from conceptual_backup)");
        pstmt.execute();
        ResultSet rs = pstmt.getResultSet();
        
        ConceptualBackupBO object = new ConceptualBackupBO();
        
        if (rs.next()) {
            object.setId(rs.getString("conceptual_backup_id"));
            object.setPrice(rs.getDouble("price"));
            object.setDate(rs.getDate("date_made"));
            
            
            
            // Sets already in database
            object.setObjectAlreadyInDB(true);
            
            
            
        }
        return object;
    } 
    
    
}




